<template>
  <el-dialog
    :model-value="dialogAdd"
    width="40%"
    title="视频详情-添加"
    :before-close="handleClose"
  >
    <el-divider />
    <!-- 添加表单内容 -->
    <el-form :model="form" ref="formRef" :rules="rules" label-width="120px">
      <el-form-item label="视频名称：" prop="title">
        <el-input v-model="form.title" placeholder="请输入视频名称" />
      </el-form-item>

      <el-form-item label="封面图片：" prop="coverUrl">
        <el-upload
          class="upload-box"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleCoverChange"
          :on-remove="handleCoverRemove"
          accept="image/jpeg,image/png,image/gif,image/jpg"
        >
          <template v-if="form.coverUrl">
            <img :src="form.coverUrl" class="preview-image" />
            <div class="delete-icon" @click.stop="handleCoverRemove">
              <el-icon><Delete /></el-icon>
            </div>
          </template>
          <div v-else class="upload-placeholder">
            <el-icon><Plus /></el-icon>
            <span>点击上传</span>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频介绍：" prop="videoIntro">
        <WangEditor
          v-model="form.videoIntro"
          height="200"
          @change="handleEditorChange"
        />
      </el-form-item>
      <el-form-item label="视频来源：">
        <el-tabs
          v-model="videoSource"
          class="video-source-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="本地视频" name="0">
            <div class="video-input-box">
              <el-input
                v-model="form.url"
                placeholder="视频URL"
                readonly
                v-show="videoSource === '0'"
              >
                <template #append>
                  <el-upload
                    class="upload-button"
                    action="#"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="handleVideoChange"
                    accept="video/*"
                    :disabled="localVideoDisabled && !form.url"
                  >
                    <el-button
                      class="upload-btn"
                      :disabled="localVideoDisabled && !form.url"
                    >
                      添加视频
                    </el-button>
                  </el-upload>
                </template>
              </el-input>
              <div v-if="form.url && videoSource === '0'" class="video-info">
                <div class="video-file">
                  <el-icon class="video-icon"><VideoPlay /></el-icon>
                  <span class="video-name">{{ videoName }}</span>
                </div>
                <el-icon class="delete-icon" @click="handleVideoRemove">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="b站视频" name="1">
            <div>
              <el-input
                v-model="biliVideo.biliId"
                placeholder="请输入BV号，例如：BV1GJ411x7h7"
                @change="handleBiliChange"
                v-show="videoSource === '1'"
                :disabled="biliVideoDisabled && !biliVideo.biliId"
              />
              <div
                v-if="biliVideo.biliUrl && videoSource === '1'"
                class="video-info"
              >
                <div class="video-file">
                  <el-icon class="video-icon"><VideoPlay /></el-icon>
                  <span class="video-name">{{ biliVideo.biliId }}</span>
                </div>
                <el-icon class="delete-icon" @click="handleBiliRemove">
                  <Delete />
                </el-icon>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="发布状态：" prop="releaseStatus">
        <el-select v-model="form.releaseStatus" placeholder="请选择">
          <el-option :label="'草稿'" :value="0" />
          <el-option :label="'已发布'" :value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="空间名称：">
        <el-select v-model="form.spaceIdList" placeholder="请选择" multiple>
          <el-option
            v-for="item in getSpaceListAll"
            :key="item.spaceId"
            :label="item.name"
            :value="item.spaceId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup title="AddFacilityDialog">
import { uploadPic, uploadVideo } from '@/api/Upload/upload';
import { ref, onMounted, onUpdated, computed, nextTick } from 'vue';
import WangEditor from '@/components/WangEditor/index.vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete, VideoPlay } from '@element-plus/icons-vue';
import { addVideoModify, getSpaceList } from '@/api/Venue/video';

// 定义 props
const props = defineProps({
  dialogAdd: {
    type: Boolean,
  },
});

// 定义 emits
const emit = defineEmits(['confirm', 'cancel']);

const form = ref({
  title: '',
  coverUrl: '',
  url: '',
  releaseStatus: undefined,
  videoIntro: '',
  spaceIdList: [],
});
const videoSource = ref('0');
const disabled = computed(() => {
  return form.value.url ? true : false;
});
const getSpaceListAll = ref([]);
const biliVideo = ref({
  biliId: '',
  biliUrl: '',
});
const rules = {
  title: [{ required: true, message: '请输入视频名称', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '请上传封面图片', trigger: 'change' }],
  videoIntro: [
    { required: true, message: '请输入视频介绍', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '<p><br></p>') {
          callback(new Error('请输入视频介绍'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  releaseStatus: [
    { required: true, message: '请选择发布状态', trigger: 'change' },
  ],
};
const formRef = ref(null);
// 定义 emits，向父组件发送事件
const videoName = ref('');

// 添加图片格式校验函数
const validateImageType = (file) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！');
    return false;
  }
  return true;
};

// 修改封面图片上传处理
const handleCoverChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);
  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      form.value.coverUrl = response.data.data.url;
      ElMessage.success('上传成功');
      await formRef.value?.validateField('coverUrl');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 处理封面图片删除
const handleCoverRemove = () => {
  form.value.coverUrl = '';
};
// 处理取消按钮的点击事件
const handleCancel = () => {
  form.value = {
    title: '',
    coverUrl: '',
    url: '',
    releaseStatus: undefined,
    videoIntro: '',
    spaceIdList: [],
  };
  biliVideo.value = {
    biliId: '',
    biliUrl: '',
  };
  formRef.value?.resetFields();
  emit('cancel');
};

// 修改确认按钮的处理函数
const handleConfirm = async () => {
  try {
    // 表单验证
    await formRef.value?.validate();

    // 根据视频来源构建提交数据
    const submitData = {
      ...form.value,
      mediaType: videoSource.value === '0' ? '0' : '1',
    };

    // 根据视频来源设置 URL
    if (videoSource.value === '1') {
      // B站视频
      submitData.url = `player.bilibili.com/player.html?bvid=${biliVideo.value.biliId}`;
    }

    const res = await addVideoModify(submitData);
    if (res.data.code === 200) {
      ElMessage.success('添加成功');
      emit('confirm');
      handleCancel();
    } else {
      ElMessage.error(res.data.msg || '添加失败');
    }
  } catch (error) {
    if (error.message) {
      ElMessage.warning('请填写完整信息');
    } else {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    }
  }
};

// 获取空间下拉
const getSpaceOption = async () => {
  const res = await getSpaceList();
  if (res.data.code === 200) {
    getSpaceListAll.value = res.data.data || [];
  }
};
// 处理编辑器内容变化
const handleEditorChange = (html) => {
  form.value.videoIntro = html;
  // 手动触发表单验证
  formRef.value?.validateField('videoIntro');
};

// 修改视频上传处理函数
const handleVideoChange = async (file) => {
  // 添加文件类型和大小检查
  const isVideo = file.raw.type.startsWith('video/');
  const isLt500M = file.raw.size / 1024 / 1024 < 300;

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!');
    return;
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 300MB!');
    return;
  }

  const formData = new FormData();
  formData.append('video', file.raw); // 修改参数名为'video'

  try {
    ElMessage({
      message: '视频上传中...',
      type: 'info',
    });

    const response = await uploadVideo(formData);
    if (response.data.code === 200) {
      form.value.url = response.data.data.url;
      videoName.value = file.raw.name; // 保存视频名称
      ElMessage.success('上传成功');
      await formRef.value?.validateField('url');
    } else {
      ElMessage.error(response.data.msg || '上传失败');
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error(
      error.response?.data?.msg || '上传失败，请检查网络或文件大小'
    );
  }
};

// 添加视频删除处理函数
const handleVideoRemove = () => {
  form.value.url = '';
  videoName.value = '';
};
const handleClick = (tab) => {
  try {
    const newSource = tab.props.name;
    if (newSource === videoSource.value) return;

    videoSource.value = newSource;
  } catch (error) {
    console.error('标签切换出错:', error);
  }
};
// 关闭对话框
const handleClose = () => {
  handleCancel();
};

// 修改B站视频ID变化处理函数
const handleBiliChange = (value) => {
  if (!value) {
    handleBiliRemove();
    return;
  }

  // 验证BV号格式
  if (!value.startsWith('BV')) {
    ElMessage.error('请输入正确的BV号格式');
    return;
  }

  // 只更新 biliVideo 的数据，不更新 form.url
  biliVideo.value.biliUrl = `//player.bilibili.com/player.html?bvid=${value}&page=1`;
  ElMessage.success('添加成功');
};

// 处理B站视频移除
const handleBiliRemove = () => {
  biliVideo.value.biliId = '';
  biliVideo.value.biliUrl = '';
  form.value.url = '';
};

// 修改计算属性，分别控制本地视频和B站视频的禁用状态
const localVideoDisabled = computed(() => {
  return biliVideo.value.biliId !== '' || form.value.url !== '';
});

const biliVideoDisabled = computed(() => {
  return form.value.url !== '' || biliVideo.value.biliId !== '';
});

onMounted(() => {});
onUpdated(() => {
  getSpaceOption();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.upload-box {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
  }

  .upload-placeholder {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    color: #8c8c8c;

    .el-icon {
      font-size: 20px;
      margin-bottom: 8px;
    }

    span {
      display: block;
      font-size: 12px;
    }
  }

  .delete-icon {
    position: absolute;
    top: 0;
    right: 0;
    width: 24px;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
    border-bottom-left-radius: 8px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }

  &:hover .delete-icon {
    opacity: 1;
  }
}

:deep(.editor-container) {
  margin-bottom: 20px;
}
.video-source-tabs {
  width: 100%;

  :deep(.el-tabs__content) {
    width: 100%;
  }

  :deep(.el-tab-pane) {
    width: 100%;
  }

  .video-input-box,
  .video-info {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .video-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 6px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .video-file {
        display: flex;
        align-items: center;
        gap: 6px;

        .video-icon {
          color: #409eff;
          font-size: 14px;
          display: inline-flex;
          align-items: center;
        }

        .video-name {
          color: #606266;
          font-size: 14px;
          line-height: 14px;
        }
      }

      .delete-icon {
        color: #f56c6c;
        font-size: 14px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.3s ease;

        &:hover {
          color: #fff;
          background-color: #f56c6c;
        }
      }
    }
  }

  .el-tab-pane {
    .video-info {
      margin-top: 8px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 6px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .video-file {
        display: flex;
        align-items: center;
        gap: 6px;

        .video-icon {
          color: #409eff;
          font-size: 14px;
          display: inline-flex;
          align-items: center;
        }

        .video-name {
          color: #606266;
          font-size: 14px;
          line-height: 14px;
        }
      }

      .delete-icon {
        color: #f56c6c;
        font-size: 14px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.3s ease;

        &:hover {
          color: #fff;
          background-color: #f56c6c;
        }
      }
    }
  }

  .video-input-box {
    width: 100%;

    :deep(.el-input-group__append) {
      padding: 0;
      background-color: transparent;
      border: none;

      .upload-button {
        display: block;
        width: 100%;

        .el-upload {
          display: block;
          width: 100%;
        }

        .upload-btn {
          width: 100%;
          margin: 0;
          height: 32px;
          padding: 0 15px;
          background-color: #409eff;
          border-color: #409eff;
          color: #fff;
          border: none;
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;

          &:hover:not(:disabled) {
            background-color: #66b1ff;
            border-color: #66b1ff;
          }

          &:disabled {
            background-color: #409eff;
            opacity: 0.6;
            cursor: not-allowed;
          }
        }
      }
    }

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;

      &.is-disabled {
        box-shadow: 0 0 0 1px #e4e7ed inset;
        background-color: #f5f7fa;
      }
    }
  }
}

// 添加禁用状态的样式
:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>
